package com.spring.bean.register;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;

@Slf4j
public class CustomerScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry beanDefinitionRegistry, BeanNameGenerator importBeanNameGenerator) {
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(BeanScan.class.getName()));
        String[] rpcScanBasePackages = new String[0];
        if(annotationAttributes != null){
            rpcScanBasePackages =  annotationAttributes.getStringArray("basePackage");
        }
        if(rpcScanBasePackages.length <= 0 ){
            rpcScanBasePackages = new String[]{((StandardAnnotationMetadata)importingClassMetadata).getIntrospectedClass().getPackage().getName()};
        }
        CustomerScanner customerScanner = new CustomerScanner(beanDefinitionRegistry, BeanScan.class);

        if(resourceLoader != null){
            customerScanner.setResourceLoader(resourceLoader);
        }

        int rpcServiceCount = customerScanner.scan(rpcScanBasePackages);
        log.info("customerScanner 扫描的数量 [{}]", rpcServiceCount);
    }
}
